package cn.org.seventh.web.common;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.org.seventh.common.StringUtil;
import cn.org.seventh.common.VerifyCodeImage;

/**
 * @author <a href="mailto:ji.li@symbio-group.com">Andy</a>
 * @since Dec 3, 2007 10:52:32 AM
 */
public final class VerifyCodeImageServlet extends HttpServlet {

	private static final long serialVersionUID = 1809757120348352807L;

	public static String VERIFY_CODE = "_VERIFY_CODE";

	/**
	 * Route the user to the execute method
	 * 
	 * @param request
	 *            The HTTP request we are processing
	 * @param response
	 *            The HTTP response we are creating
	 * @exception IOException
	 *                if an input/output error occurs
	 * @exception ServletException
	 *                if a servlet exception occurs
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		execute(request, response);
	}

	/**
	 * Route the user to the execute method
	 * 
	 * @param request
	 *            The HTTP request we are processing
	 * @param response
	 *            The HTTP response we are creating
	 * @exception IOException
	 *                if an input/output error occurs
	 * @exception ServletException
	 *                if a servlet exception occurs
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		execute(request, response);
	}

	/**
	 * Process the specified HTTP request, and create the corresponding HTTP
	 * response (or forward to another web component that will create it).
	 * 
	 * @param request
	 *            The HTTP request we are processing
	 * @param response
	 *            The HTTP response we are creating
	 * @exception IOException
	 *                if an input/output error occurs
	 * @exception ServletException
	 *                if a servlet exception occurs
	 */
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String s = StringUtil.createVerifyCode();
		// if (Math.random() > 0.7) {
		// s = "WMWM";
		// } else if (Math.random() > 0.7) {
		// s = "MWMW";
		// }
		VerifyCodeImage vi = new VerifyCodeImage(s);
		response.setContentType("image/png");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		request.getSession().setAttribute(VERIFY_CODE, s);
		ImageIO.write(vi.getImage(), "png", response.getOutputStream());
	}
}
